// 部署脚本 - 用于将ERC20代币部署到Sepolia测试网
// 使用前请确保安装必要的依赖: npm install ethers dotenv

const { ethers } = require('ethers');
const fs = require('fs');
require('dotenv').config();

// 配置信息
const config = {
    // 代币基本信息
    TOKEN_NAME: "MyLearningToken",
    TOKEN_SYMBOL: "MLT",
    TOKEN_DECIMALS: 18,
    INITIAL_SUPPLY: 1000000, // 100万代币

    // 网络配置
    SEPOLIA_RPC_URL: process.env.SEPOLIA_RPC_URL || "https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID",
    PRIVATE_KEY: process.env.PRIVATE_KEY, // 您的私钥（请通过环境变量设置）

    // Gas配置
    GAS_LIMIT: 3000000,
    GAS_PRICE: ethers.utils.parseUnits('20', 'gwei')
};

// 合约ABI（只包含我们需要的函数）
const contractABI = [
    "constructor(string memory _name, string memory _symbol, uint8 _decimals, uint256 _initialSupply)",
    "function name() public view returns (string)",
    "function symbol() public view returns (string)",
    "function decimals() public view returns (uint8)",
    "function totalSupply() public view returns (uint256)",
    "function balanceOf(address account) public view returns (uint256)",
    "function transfer(address to, uint256 amount) public returns (bool)",
    "function approve(address spender, uint256 amount) public returns (bool)",
    "function allowance(address owner, address spender) public view returns (uint256)",
    "function transferFrom(address from, address to, uint256 amount) public returns (bool)",
    "function mint(address to, uint256 amount) public",
    "function owner() public view returns (address)",
    "event Transfer(address indexed from, address indexed to, uint256 value)",
    "event Approval(address indexed owner, address indexed spender, uint256 value)"
];

// 合约字节码（请将编译后的bytecode粘贴到这里）
const contractBytecode = `
请将您编译后的合约字节码粘贴到这里。
您可以使用以下方式获取字节码：
1. 使用 Remix IDE 编译合约
2. 使用 Hardhat: npx hardhat compile
3. 使用 Truffle: truffle compile
`;

async function deployContract() {
    try {
        console.log("🚀 开始部署 ERC20 代币合约到 Sepolia 测试网...\n");

        // 检查必要的环境变量
        if (!config.PRIVATE_KEY) {
            throw new Error("请设置 PRIVATE_KEY 环境变量");
        }

        // 连接到 Sepolia 测试网
        const provider = new ethers.providers.JsonRpcProvider(config.SEPOLIA_RPC_URL);
        const wallet = new ethers.Wallet(config.PRIVATE_KEY, provider);

        console.log("📡 连接信息:");
        console.log("- 网络:", await provider.getNetwork());
        console.log("- 部署地址:", wallet.address);
        console.log("- 余额:", ethers.utils.formatEther(await wallet.getBalance()), "ETH\n");

        // 检查余额是否足够
        const balance = await wallet.getBalance();
        const estimatedCost = config.GAS_LIMIT * config.GAS_PRICE;
        if (balance.lt(estimatedCost)) {
            console.warn("⚠️  警告: 账户余额可能不足以支付gas费用");
            console.log("- 预估费用:", ethers.utils.formatEther(estimatedCost), "ETH");
            console.log("- 当前余额:", ethers.utils.formatEther(balance), "ETH\n");
        }

        // 创建合约工厂
        const contractFactory = new ethers.ContractFactory(
            contractABI,
            contractBytecode,
            wallet
        );

        console.log("📋 代币参数:");
        console.log("- 名称:", config.TOKEN_NAME);
        console.log("- 符号:", config.TOKEN_SYMBOL);
        console.log("- 小数位:", config.TOKEN_DECIMALS);
        console.log("- 初始供应量:", config.INITIAL_SUPPLY.toLocaleString(), "代币\n");

        // 部署合约
        console.log("⏳ 正在部署合约...");
        const contract = await contractFactory.deploy(
            config.TOKEN_NAME,
            config.TOKEN_SYMBOL,
            config.TOKEN_DECIMALS,
            config.INITIAL_SUPPLY,
            {
                gasLimit: config.GAS_LIMIT,
                gasPrice: config.GAS_PRICE
            }
        );

        console.log("🔄 等待交易确认...");
        console.log("- 交易哈希:", contract.deployTransaction.hash);

        // 等待合约部署完成
        await contract.deployed();

        console.log("\n✅ 合约部署成功!");
        console.log("- 合约地址:", contract.address);
        console.log("- 区块号:", contract.deployTransaction.blockNumber);
        console.log("- Gas 使用量:", contract.deployTransaction.gasLimit.toString());

        // 验证合约部署
        console.log("\n🔍 验证合约信息:");
        const name = await contract.name();
        const symbol = await contract.symbol();
        const decimals = await contract.decimals();
        const totalSupply = await contract.totalSupply();
        const owner = await contract.owner();

        console.log("- 代币名称:", name);
        console.log("- 代币符号:", symbol);
        console.log("- 小数位数:", decimals.toString());
        console.log("- 总供应量:", ethers.utils.formatUnits(totalSupply, decimals));
        console.log("- 合约所有者:", owner);

        // 保存部署信息
        const deploymentInfo = {
            contractAddress: contract.address,
            deploymentHash: contract.deployTransaction.hash,
            deploymentBlock: contract.deployTransaction.blockNumber,
            deployer: wallet.address,
            network: "sepolia",
            timestamp: new Date().toISOString(),
            tokenInfo: {
                name,
                symbol,
                decimals: decimals.toString(),
                totalSupply: totalSupply.toString()
            }
        };

        fs.writeFileSync(
            'deployment-info.json',
            JSON.stringify(deploymentInfo, null, 2)
        );

        console.log("\n📄 部署信息已保存到 deployment-info.json");

        // 生成添加到钱包的信息
        console.log("\n🦊 添加代币到 MetaMask:");
        console.log("- 代币合约地址:", contract.address);
        console.log("- 代币符号:", symbol);
        console.log("- 小数位数:", decimals.toString());
        console.log("\n📱 可以复制以上信息到您的钱包中导入代币");

        // 生成Etherscan链接
        console.log("\n🔗 Etherscan 链接:");
        console.log("- 合约:", `https://sepolia.etherscan.io/address/${contract.address}`);
        console.log("- 交易:", `https://sepolia.etherscan.io/tx/${contract.deployTransaction.hash}`);

        return contract;

    } catch (error) {
        console.error("❌ 部署失败:", error.message);
        if (error.code === 'INSUFFICIENT_FUNDS') {
            console.log("\n💡 解决方案:");
            console.log("1. 获取 Sepolia 测试币: https://sepoliafaucet.com/");
            console.log("2. 或使用其他水龙头: https://faucets.chain.link/sepolia");
        }
        throw error;
    }
}

// 运行部署脚本
if (require.main === module) {
    deployContract()
        .then(() => {
            console.log("\n🎉 部署完成!");
            process.exit(0);
        })
        .catch((error) => {
            console.error("部署失败:", error);
            process.exit(1);
        });
}

module.exports = { deployContract, config };
